<p> Name: <%= @questionnaire.name %>                                    </p>
<p> Maximum time: <%= pluralize(@max_hours, 'hour') +' '+ pluralize(@max_minutes, 'minute') %> </p>
<p> Created at: <%= @questionnaire.created_at.to_formatted_s(:short) %> </p>
<p> Created by: <%= @questionnaire.user.login %> </p>

<% form_tag correct_questionnaire_path(@questionnaire) do |f| %>
  <%= render :partial => 'question', :collection => @questionnaire.questions, :locals => {:corrections => nil} %>
  <p> <%= submit_tag 'Correct questionnaire' %> </p>
<% end %>

<div id="timer" style="width:10%;float:right">  </div>

<script type="text/javascript"> // Time countdown
  remainingTime = <%= @remainingTime %>;
  
  function getElementsByClass(theClass, container) {
    container = container || document;
    var all = container.all || container.getElementsByTagName('*');
    var selected = [];
    for (var i = 0; i < all.length; i++) {
      if (all[i].className == theClass) {
        selected[selected.length] = all[i];
      }
    }
    return selected;
  }
  
  function recursiveForChildrenFunction(func) {
    return resultFunction = function(element) {
      $(func)(element);
      if (element.childNodes && element.childNodes.length > 0) {
        for (var i = 0; i < element.childNodes.length; i++) {
          resultFunction(element.childNodes[i]);
        }
      }
    }
  }
  
  function disableElement(element) {
    $(element).disabled = true;
  }
  
  function enableElement(element) {
    $(element).disabled = false;
  }
  
  function uncheckElement(element) {
    $(element).checked = false;
  }
  
  function hoursAndMinutes(time) {
    var theTime = time;
    var seconds = theTime % 60;
    theTime -= seconds;
    var minutes = theTime % 3600;
    theTime -= minutes;
    minutes /= 60;
    var hours = theTime / 3600;
    return hours + "h " + minutes + "m " + seconds + "s";
  }

  function countdown() {
    document.getElementById("timer").innerHTML = "Remaining time: " + hoursAndMinutes(remainingTime); 
    if (remainingTime > 0) {
      remainingTime--;
      setTimeout(countdown, 1000);
    } else {
      getElementsByClass("answer").map(recursiveForChildrenFunction(disableElement));
      alert("Time is over.\nAnswering disabled\n Press 'Correct questionnaire' to see your score");
    }
  }
  getElementsByClass("answer").map(recursiveForChildrenFunction(uncheckElement));
  getElementsByClass("answer").map(recursiveForChildrenFunction(enableElement));
  if (remainingTime > 0) countdown();
</script>

<div id=links_section>
  <%= link_to 'Back to questionnaire page', questionnaire_path %>
  <%= link_to 'Back to \'List of Questionnaires\'', questionnaires_path %>
</div>